package cn.javass.struts2impl.interceptor;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.ServletDispatcherResult;

import cn.javass.struts2impl.preResultListener.MyPreResult;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoggerInterceptor implements Interceptor {

    private final Logger logger = Logger.getLogger(this.getClass());
    
    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void init() {
        // TODO Auto-generated method stub

    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // 注册调用PreResultListener
//        invocation.addPreResultListener(new MyPreResult());
        
        logger.info("=====logger begin====================================");
        // 找到运行的Action请求名称，并打印其名称
        logger.info("**Action:" + invocation.getInvocationContext().getName());
        ActionContext ac = invocation.getInvocationContext();
        // 找到运行的Action对象，并打印其名称
        logger.info("**Class:" + invocation.getAction().getClass().getName());
        // 找到运行的ActionProxy对象，并打印其要运行的方法名
        logger.info("**Method:" + invocation.getProxy().getMethod());
        // 找到这次请求的request中的parameter参数，并打印
        Map<String, Object> params = invocation.getInvocationContext().getParameters();
        for(String key : params.keySet()){
            Object obj = params.get(key);
            if(obj instanceof String[]){
                String[] arr = (String[]) obj;
                logger.info("**Param:" + key);
                for(String value : arr){
                    logger.info("  >>>>>>" + value);
                }
            }
        }
        
        // 运行后续的拦截器、Action、Result
        logger.info("-----invoke begin------------------------------------");
        String returnCode = invocation.invoke();
        logger.info("-----invoke end--------------------------------------");
        
        // 在Action、Result运行之后，得到Result对象
        // 并且可以强制转换成ServletDispatcherResult，打印其下一个JSP的位置
        Result rresult = invocation.getResult();
        if(rresult instanceof ServletDispatcherResult){
            ServletDispatcherResult result = (ServletDispatcherResult) rresult;
            logger.info("**JSP:" + result.getLastFinalLocation());
        }
        
        return returnCode;
    }

}
